package com.example.springbootServiceNetwork.demos.web.Service.Impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.springbootServiceNetwork.demos.web.Config.JwtInfo;
import com.example.springbootServiceNetwork.demos.web.Config.Result;
import com.example.springbootServiceNetwork.demos.web.Config.SparkApiConfig;
import com.example.springbootServiceNetwork.demos.web.Dao.LargeModeDao;
import com.example.springbootServiceNetwork.demos.web.Dao.SparkChatDao;
import com.example.springbootServiceNetwork.demos.web.Dto.SparkParamDto;
import com.example.springbootServiceNetwork.demos.web.Entity.LargeModel;
import com.example.springbootServiceNetwork.demos.web.Entity.SparkChat;
import com.example.springbootServiceNetwork.demos.web.Service.SparkService;
import okhttp3.*;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

import static com.example.springbootServiceNetwork.demos.web.Tool.SparkUtil.*;

@Service
public class SparkServiceImpl implements SparkService {
    @Resource
    private SparkApiConfig sparkApiConfig;

    @Resource
    private SparkChatDao sparkChatDao;

    @Resource
    private LargeModeDao largeModeDao;




    /**
     * 发起post会话
     * @param sparkParamDto
     * @param jwtInfo
     * @return
     */
    @Override
    public Result SparkChat(SparkParamDto sparkParamDto, JwtInfo jwtInfo) {
            Result result = new Result();
            try {
                // 构建鉴权url
                String authUrl = getAuthUrl(sparkApiConfig.getHostUrl(), sparkApiConfig.getApiKey(), sparkApiConfig.getApiSecret());
                OkHttpClient client = new OkHttpClient.Builder().build();
                String url = authUrl.toString().replace("http://", "ws://").replace("https://", "wss://");
                Request request = new Request.Builder().url(url).build();
                String body = getSparkJson(jwtInfo, sparkApiConfig.getAppId(),sparkParamDto);

                StringBuilder builderSb =new StringBuilder();
                CompletableFuture<String> messageReceived = new CompletableFuture<>();

                WebSocket webSocket = client.newWebSocket(request, new WebSocketListener(){

                    @Override
                    public void onOpen(WebSocket webSocket, Response response) {
                        webSocket.send(body);
                    }
                    @Override
                    public void onMessage(WebSocket webSocket, String res) {
                        JSONObject obj = JSON.parseObject(res);
                        String str= obj.getJSONObject("payload").getJSONObject("choices").getJSONArray("text").getJSONObject(0).getString("content");
                        builderSb.append(str);
                        if(obj.getJSONObject("header").getLong("status")==2){
                            webSocket.close(1000, "Closing WebSocket connection");
                            messageReceived.complete(res); // 将收到的消息传递给 CompletableFuture
                        }
                    }

                });
                String resItem = messageReceived.get(30, TimeUnit.SECONDS);// 阻塞等待消息返回
                webSocket.close(1000, "Closing WebSocket connection");
                result.setData(builderSb.toString());
                result.setCode(200);
                result.setMsg("天梦星");
            }catch (Exception e){
                e.printStackTrace();
            }
        return result;
    }

    /**
     * 新增星火会话记录
     * @param sparkChat
     * @return
     */
    @Override
    public Result addSparkChat(SparkChat sparkChat) {
        Result result = new Result();
        UUID uuid = UUID.randomUUID();
        sparkChat.setUuid(uuid.toString());
        int res = sparkChatDao.insert(sparkChat);
        if (res>=1){
            LambdaQueryWrapper<SparkChat> lqw = new LambdaQueryWrapper<>();
            lqw.eq(SparkChat::getUuid,sparkChat.getUuid());
            SparkChat sparkChat1 = sparkChatDao.selectOne(lqw);
            result.setCode(200);
            result.setMsg("会话记录新增成功！");
            result.setData(sparkChat1.getId());
        }else {
            result.setCode(400);
            result.setMsg("前端语法错误！");
        }
        return result;
    }

    /**
     * 删除星火会话记录(批量删除)
     * @param sparkChatList
     * @return
     */
    @Override
    public Result deleteSparkChat(List<SparkChat> sparkChatList) {
        Result result = new Result();
        LambdaQueryWrapper<SparkChat> lqw = new LambdaQueryWrapper<>();
        int res = sparkChatDao.deleteBatchIds(sparkChatList);
        result.setCode(200);
        result.setMsg("会话记录删除成功！");
        result.setData(res);
        return result;
    }

    /**
     * 更新星火会话记录(批量删除)
     * @param sparkChat
     * @return
     */
    @Override
    public Result updateSparkChat(SparkChat sparkChat) {
        Result result = new Result();
        int res = sparkChatDao.updateById(sparkChat);
        if (res>=1){
            result.setCode(200);
            result.setMsg("更新成功！");
        }else {
            result.setCode(400);
            result.setMsg("前端语法错误！");
        }
        return result;
    }


    /**
     * 查询星火会话记录(批量删除)
     * @param jwtInfo
     * @return
     */
    @Override
    public Result querySparkChat(JwtInfo jwtInfo) {
        Result result = new Result();
        LambdaQueryWrapper<SparkChat> lqw = new LambdaQueryWrapper<>();
        lqw.eq(SparkChat::getUserId,jwtInfo.getUserId());
        List<SparkChat> list = sparkChatDao.selectList(lqw);
        result.setData(list);
        result.setCode(200);
        result.setMsg("历史会话查询成功！");
        return result;
    }


    /**
     * 查询模型全部分类
     * @param jwtInfo
     * @return
     */
    @Override
    public Result queryAllLargeMode(JwtInfo jwtInfo) {
        Result result = new Result();
        List<LargeModel> list = largeModeDao.selectList(null);
        result.setData(list);
        result.setCode(200);
        result.setMsg("模型分类查询成功！");
        return result;
    }

    /**
     * 添加模型分类
     * @param largeModel
     */
    @Override
    public Result addLargeMode(LargeModel largeModel) {
        Result result = new Result();
        int res = largeModeDao.insert(largeModel);
        if (res>=1){
            result.setCode(200);
            result.setMsg("模型分类新增成功！");
        }else {
            result.setCode(400);
            result.setMsg("前端语法错误！");
        }
        return result;
    }

    /**
     * 更新模型分类
     * @param largeModel
     */
    @Override
    public Result updateLargeMode(LargeModel largeModel) {
        Result result = new Result();
        int res = largeModeDao.updateById(largeModel);
        if (res>=1){
            result.setCode(200);
            result.setMsg("模型分类更新成功！");
        }else {
            result.setCode(400);
            result.setMsg("前端语法错误！");
        }
        return result;
    }

    /**
     * 删除模型分类
     * @param largeModelList
     */
    @Override
    public Result deleteLargeMode(List<LargeModel> largeModelList) {
        Result result = new Result();
        LambdaQueryWrapper<LargeModel> lqw = new LambdaQueryWrapper<>();
        int res = largeModeDao.deleteBatchIds(largeModelList);
        result.setCode(200);
        result.setMsg("会话记录删除成功！");
        result.setData(res);
        return result;
    }

}
